from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
from shortuuidfield import ShortUUIDField
import re
from django.core import validators
from django.utils.deconstruct import deconstructible
from django.utils.translation import gettext_lazy as _


class UserManager(BaseUserManager):
    def __create_user(self, account, username, password, **kwargs):
        if not account:
            raise ValueError('来个有个性账号吧~~')
        if not username:
            raise ValueError('来个帅气昵称~~')
        if not password:
            raise ValueError('来个密码加密一下~~')
        user = self.model(account=account, username=username, **kwargs)
        user.set_password(password)
        user.save()
        return user

    def create_user(self, account, username, password, **kwargs):
        return self.__create_user(account, username, password, **kwargs)

    def create_superuser(self, account, username, password, **kwargs):
        kwargs['is_superuser'] = True
        return self.__create_user(account, username, password, **kwargs)


@deconstructible
class AccountValidator(validators.RegexValidator):
    regex = r'^[a-zA-Z][a-zA-Z0-9]{2, 20}$'
    message = _(
        '请输入唯一账号, 可包含英文字母和数字, 必须字母开头。 2 ~ 20 个字符。'
    )
    flags = re.ASCII


class User(AbstractBaseUser, PermissionsMixin):
    class Meta:
        db_table = "user"
        verbose_name = "用户表"
        verbose_name_plural = verbose_name

    uid = ShortUUIDField(primary_key=True)
    username = models.CharField(verbose_name="昵称",
                                max_length=20)
    account = models.CharField(verbose_name="账号",
                               max_length=20,
                               unique=True,
                               error_messages={
                                   'unique': _("该账号已存在."),
                               },
                               validators=[AccountValidator])

    email = models.EmailField(verbose_name="邮箱",
                              unique=True, null=True)
    avatar = models.URLField(verbose_name="头像", null=True)

    is_superuser = models.BooleanField(verbose_name="超级管理员",
                                       default=False)
    is_staff = models.BooleanField(verbose_name="管理员",
                                   default=False)
    is_active = models.BooleanField(verbose_name="激活状态",
                                    default=True)
    is_del = models.BooleanField(verbose_name="删除",
                                 default=False)
    join_date = models.DateTimeField(verbose_name="加入时间",
                                     auto_now_add=True)

    EMAIL_FIELD = 'email'
    USERNAME_FIELD = 'account'
    REQUIRED_FIELDS = ['username']

    objects = UserManager()

    def get_full_name(self):
        return self.username

    def get_short_name(self):
        return self.username
